package hyl.prod.task;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import hyl.core.Amy;

import hyl.core.MyFun;
import hyl.core.conf.MyConfig;
import hyl.core.io.MyFile;
import hyl.core.io.MyPath;
import hyl.core.run.MyRun;

public class TaskServer {
	static Logger logger = LoggerFactory.getLogger(TaskServer.class);
	public static Map<String, TaskBean> config = new HashMap<String, TaskBean>();
	private static final String _rootdir = MyPath.getPathOfPro() + "task_run/";
	static final int MAXTASKSIZE = 128;
	static final String _s启动配置文件 = "app.json";

	public static String getRootdir() {
		return _rootdir;
	}

	public static void main(String[] args) throws Exception {
		// 得到定时器实例
		new My();
		// MyFile.deleteDir(_rootdir);
		MyFile.openDir(_rootdir);
		Load();
		MyRun executorService = Amy.getMyRun();
		if (config.size() > MAXTASKSIZE) {
			logger.error("单组任务的子任务个数不能超过" + MAXTASKSIZE + "个");
			return;
		}
		for (String title : config.keySet()) {
			TaskBean d = config.get(title);
			executorService.execute(d);//为什么原来用call一个一个派发是有问题的
		}
	};

	// 载入配置文件,解析配置文件
	public static void Load() {
		config.clear();

		JSONObject jobj = MyConfig.loadJsonObj(_s启动配置文件, Amy.charset);
		// Map<String, Map<String, String>> pp = (Map<String, Map<String, String>>)
		// JSONObject.parse(txt);
		for (String title : jobj.keySet()) {
			// System.out.println(e.getKey());
			// System.out.println(e.getValue().get("开始日期"));
			if (title.isEmpty())
				continue;
			JSONObject p = jobj.getJSONObject(title);
			System.out.println(p.toJSONString());
			TaskBean tu = new TaskBean(title);
			String date = "";			
			
			tu.set时段格式(p.getString("时段格式")); 
			JSONArray 有效时段 = p.getJSONArray("有效时段");
			if (有效时段 != null)
				tu.set时间区间(有效时段);	
			
			date = p.getString("结束时间");
			if (!MyFun.isEmpty(date))
				tu.setEndtime(MyFun.str2Datetime(date.trim()));

			date = p.getString("开始时间");
			// System.out.println("开始时间"+date);
			if (!MyFun.isEmpty(date))
				tu.setStarttime(MyFun.str2Datetime(date.trim()));
						
			tu.set下一次运行间隔秒(p.get("下一次间隔(秒)"));

			tu.set重试次数(p.get("重试次数"));//set顺序不能错,先次数后间隔
			tu.set重试间隔秒(p.get("重试间隔(秒)"));
			tu.set超时(p.getJSONArray("超时"));
			
			tu.set异常后终止(p.get("异常后终止"));
			
			tu.set成功字符(p.get("成功字符"));
			
			tu.set依赖任务(p.getString("依赖"));

			tu.setJarFile(p.getString("jar"));

			tu.setJarMethod(p.getString("method"));

			tu._IsStaticFun = MyFun.str2Bool(p.getString("static"));

			tu.setJarClass(p.getString("class"));

			tu.setUrl(p.getString("url"));

			tu.setCmd(p.getString("cmd"));

			tu.setSql(p.getString("sql"));

			tu.setParams(p.getJSONArray("params"));

			tu.setDb(p.getString("db"));

			tu.getTlog().f初始化任务状态();
			//System.out.println(tu.getStarttime());
			//System.out.println(tu.getEndtime());
			config.put(title, tu);
		}

	}
}
